import axios from "axios";
import router from "@/router";

axios.defaults.timeout = 2000;
// request拦截器，将用户token放入头中
const token = sessionStorage.getItem("token");

axios.interceptors.request.use(
    config => {
        console.log("得到的token为"+token)
        if(token) config.headers['token'] = token
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)
axios.interceptors.response.use(function (response) {
    console.log("response"+response.data.success)
    // 判断执行结果
    if (!response.data.success) {
        return Promise.reject(response.data.errorMsg)
    }
    return response.data;
}, function (error) {
    // 一般是服务端异常或者网络异常
    console.log(error)
    if(error.response.status == 409){
        // 未登录，跳转
        setTimeout(() => {
            router.push({ path: "/user/login" });
        }, 200);
        return Promise.reject("请先登录");
    }
    return Promise.reject("服务器异常");
});